<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="名称" prop="shiftName">
            <el-input v-model="queryParams.shiftName" placeholder="请输入名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['dormitory:shift:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['dormitory:shift:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['dormitory:shift:remove']"
              >删除</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['dormitory:shift:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table height="calc(100vh - 370px)" v-loading="loading" :data="shiftList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="班次名称" align="center" prop="shiftName" />
        <el-table-column label="考勤类型" align="center" prop="attendanceType">
          <template #default="scope">
            <dict-tag :options="attendance_shift_type" :value="scope.row.attendanceType" />
          </template>
        </el-table-column>
        <el-table-column label="考勤时段" align="center" prop="shiftSegments" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['dormitory:shift:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dormitory:shift:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改考勤班次对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="750px" append-to-body>
      <el-form ref="shiftFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班次名称" prop="shiftName">
          <el-input v-model="form.shiftName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="考勤时间段" prop="comeLateMinutes" label-width="93px">
          <el-tabs v-model="activeName" class="demo-tabs" style="width: 100%">
            <el-tab-pane :label="shift.label" :name="shift.attendanceType" v-for="shift of attendanceShifts">
              <template v-for="segment of shift.segments">
                <el-row style="padding-bottom: 5px">
                  <el-col :span="8">
                    <el-form-item :label="segment.period[0]+'入寝'">
                      <el-time-picker
                        v-model="segment.startTime"
                        format="HH:mm"
                        value-format="HH:mm"
                        style="width: 100px"
                        @change="handleTimeChange"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item>
                      <el-time-picker
                        v-model="segment.signInStart"
                        format="HH:mm"
                        value-format="HH:mm"
                        style="width: 100px"
                        @change="handleTimeChange"
                      />
                      <span style="padding-left: 5px; padding-right: 5px">至</span>
                      <el-time-picker
                        v-model="segment.signInEnd"
                        format="HH:mm"
                        value-format="HH:mm"
                        style="width: 100px"
                        @change="handleTimeChange"
                      />
                      <span style="padding-left: 5px; padding-right: 5px">可签到</span>
                    </el-form-item>
                  </el-col>
                  <p class="tipText" v-if="segment.tipInText">{{ segment.tipInText }}</p>
                </el-row>
                <el-row style="padding-bottom: 20px">
                  <el-col :span="8">
                    <el-form-item :label="segment.period[1]+'出寝'">
                      <el-time-picker v-model="segment.endTime" format="HH:mm" value-format="HH:mm" style="width: 100px" @change="handleTimeChange" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item>
                      <el-time-picker
                        v-model="segment.signOutStart"
                        format="HH:mm"
                        value-format="HH:mm"
                        style="width: 100px"
                        @change="handleTimeChange"
                      />
                      <span style="padding-left: 5px; padding-right: 5px">至</span>
                      <el-time-picker
                        v-model="segment.signOutEnd"
                        format="HH:mm"
                        value-format="HH:mm"
                        style="width: 100px"
                        @change="handleTimeChange"
                      />
                      <span style="padding-left: 5px; padding-right: 5px">可签退</span>
                    </el-form-item>
                  </el-col>
                  <p class="tipText" v-if="segment.tipOutText">{{ segment.tipOutText }}</p>
                </el-row>
              </template>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        <el-form-item prop="leaveEarlyMinutes">
          深夜未归告警设置: 超过
          <el-time-picker
            v-model="form.alarmTime"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 120px; padding-left: 10px; padding-right: 10px"
          />
          告警提醒
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Shift" lang="ts">
import { listShift, getShift, delShift, addShift, updateShift } from '@/api/attendance/setting/shift';
import { ShiftVO, ShiftQuery, ShiftForm } from '@/api/attendance/setting/shift/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { attendance_shift_type } = toRefs<any>(proxy?.useDict('attendance_shift_type'));

const shiftList = ref<ShiftVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const activeName = ref('1');
const queryFormRef = ref<ElFormInstance>();
const shiftFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ShiftForm = {
  id: undefined,
  type: 2,
  shiftName: undefined,
  attendanceType: undefined,
  comeLateMinutes: 0,
  leaveEarlyMinutes: 0,
  absenceMinutes: 0,
  alarmTime: '23:59',
  remark: undefined,
  segments: []
};
const data = reactive<PageData<ShiftForm, ShiftQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: 2,
    shiftName: undefined,
    attendanceType: undefined,
    comeLateMinutes: undefined,
    leaveEarlyMinutes: undefined,
    absenceMinutes: undefined,
    alarmTime: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    shiftName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
    attendanceType: [{ required: true, message: '考勤类型不能为空', trigger: 'change' }],
    alarmTime: [{ required: true, message: '告警时间不能为空', trigger: 'blur' }]
    // remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const initSegment = {
  sortNum: 0,
  startTime: undefined,
  signInStart: undefined,
  signInEnd: undefined,
  endTime: undefined,
  signOutStart: undefined,
  signOutEnd: undefined,
  tipInText: undefined,
  tipOutText: undefined,
  period: Array<string>
};

const initAttendanceShifts = [
  {
    label: '一天一次出入寝',
    attendanceType: '1',
    segments: [{ ...initSegment, period: ['晚上', '早上'] }]
  },
  {
    label: '一天两次出入寝',
    attendanceType: '2',
    segments: [
      { ...initSegment, sortNum: 0, period: ['中午', '中午'] },
      { ...initSegment, sortNum: 1, period: ['晚上', '早上'] }
    ]
  },
  {
    label: '一天三次出入寝',
    attendanceType: '3',
    segments: [
      { ...initSegment, sortNum: 0, period: ['中午', '中午'] },
      { ...initSegment, sortNum: 1, period: ['下午', '下午'] },
      { ...initSegment, sortNum: 2, period: ['晚上', '早上'] }
    ]
  }
];

const attendanceShifts = ref([...initAttendanceShifts]);

/** 查询考勤班次列表 */
const getList = async () => {
  loading.value = true;
  const res = await listShift(queryParams.value);
  shiftList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  activeName.value = '1';
  for (let s of initAttendanceShifts) {
    for (let seg of s.segments) {
      seg.startTime = undefined;
      seg.signInStart = undefined;
      seg.signInEnd = undefined;
      seg.endTime = undefined;
      seg.signOutStart = undefined;
      seg.signOutEnd = undefined;
      seg.tipInText = undefined;
      seg.tipOutText = undefined;
    }
  }
  attendanceShifts.value = [...initAttendanceShifts];
  shiftFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ShiftVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加考勤班次';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ShiftVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getShift(_id);
  Object.assign(form.value, res.data);
  activeName.value = form.value.attendanceType;
  const shifts = initAttendanceShifts.map((obj) => Object.assign({}, obj));
  shifts.forEach((e) => {
    if (e.attendanceType === activeName.value) {
      const segments = form.value.segments;
      if (segments.length == 1) {
        segments[0]['period'] = ['晚上', '早上'];
      } else if (segments.length == 2) {
        segments[0]['period'] = ['中午', '中午'];
        segments[1]['period'] = ['晚上', '早上'];
      } else if (segments.length == 3) {
        segments[0]['period'] = ['中午', '中午'];
        segments[1]['period'] = ['下午', '下午'];
        segments[2]['period'] = ['晚上', '早上'];
      }
      e.segments = segments;
    }
  });
  attendanceShifts.value = shifts;
  dialog.visible = true;
  dialog.title = '修改考勤班次';
};

/** 提交按钮 */
const submitForm = () => {
  shiftFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (!handleTimeChange(null, true)) {
        return;
      }
      buttonLoading.value = true;
      form.value.attendanceType = activeName.value;
      form.value.segments = attendanceShifts.value.find((e) => e.attendanceType === activeName.value)?.segments;
      if (form.value.id) {
        await updateShift(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addShift(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ShiftVO) => {
  const _ids = row?.id || ids.value;
  let tipText = '是否确认删除选中的数据？';
  if (row?.id) {
    tipText = '是否确认删除"' + row.shiftName + '"的数据项？';
  }
  await proxy?.$modal.confirm(tipText).finally(() => (loading.value = false));
  await delShift(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const timeRange = (beginTime, endTime, nowTime) => {
  var strb = beginTime.split(':');
  if (strb.length != 2) {
    return false;
  }

  var stre = endTime.split(':');
  if (stre.length != 2) {
    return false;
  }

  var strn = nowTime.split(':');
  if (stre.length != 2) {
    return false;
  }
  var b = new Date();
  var e = new Date();
  var n = new Date();

  b.setHours(strb[0]);
  b.setMinutes(strb[1]);
  e.setHours(stre[0]);
  e.setMinutes(stre[1]);
  n.setHours(strn[0]);
  n.setMinutes(strn[1]);

  if (n.getTime() - b.getTime() >= 0 && n.getTime() - e.getTime() <= 0) {
    return true;
  } else {
    // alert('当前时间是：' + n.getHours() + ':' + n.getMinutes() + '，不在该时间范围内！');
    return false;
  }
};

const handleTimeChange = (val: any, isSubmit: Boolean = false) => {
  let result = true;
  for (let s of attendanceShifts.value) {
    if (activeName.value != s.attendanceType) continue;
    for (let segment of s.segments) {
      if (segment.startTime) {
        if (segment.signInStart && segment.signInEnd) {
          if (timeRange(segment.signInStart, segment.signInEnd, segment.startTime)) {
            segment.tipInText = '';
          } else {
            segment.tipInText = '签到时间必须在时间范围内';
            result = false;
          }
        } else if (isSubmit) {
          segment.tipInText = '签到时间不能为空';
          result = false;
        }
      } else if (isSubmit) {
        segment.tipInText = '签到时间不能为空';
        result = false;
      }
      if (segment.endTime) {
        if (segment.signOutStart && segment.signOutEnd) {
          if (timeRange(segment.signOutStart, segment.signOutEnd, segment.endTime)) {
            segment.tipOutText = '';
          } else {
            segment.tipOutText = '签退时间必须在时间范围内';
            result = false;
          }
        } else if (isSubmit) {
          segment.tipOutText = '签退时间不能为空';
          result = false;
        }
      } else if (isSubmit) {
        segment.tipOutText = '签退时间不能为空';
        result = false;
      }
    }
  }
  return result;
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'attendance/shift/export',
    {
      ...queryParams.value
    },
    `shift_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>

<style lang="sass" scoped>
.tipText
  color: var(--el-color-danger)
  font-size: 12px
  line-height: 1
  padding: 0
  margin: 5px
  padding-left: 80px
</style>
